package com.cenntro.auth.shiro;

import java.io.Serializable;

import javax.annotation.Resource;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.stereotype.Component;

import com.cenntro.auth.shiro.cache.ObjectSerializer;
import com.cenntro.common.redis.IRedisService;

import lombok.extern.slf4j.Slf4j;


/**
 * shiro 持久化session 到redis
 * @author Administrator
 *
 */
@Component
@Slf4j
public class RedisSessionDao extends EnterpriseCacheSessionDAO{

	@Resource
	private IRedisService redisService;
	private String prefix = "shiro_session_";
	private ObjectSerializer serializer = new ObjectSerializer();
	
	
	// 创建session，保存到数据库
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        log.info("doCreate sessionId={}", sessionId.toString());
        try {
			redisService.setObject(prefix + sessionId.toString(), serializer.serialize(session), 30*60l);
			return sessionId;
		} catch (SerializationException e) {
		}
        return null;
    }

    // 获取session
    @Override
    protected Session doReadSession(Serializable sessionId) {
        // 先从缓存中获取session，如果没有再去数据库中获取
    	log.info("doReadSession sessionId={}", sessionId.toString());
        Session session = super.doReadSession(sessionId); 
        if(session == null){
            Object se = redisService.getObject(prefix + sessionId.toString());
            if(se == null){
                return null;
            }
        	byte[] obj = (byte[])se;
        	try {
				session = (Session)serializer.deserialize(obj);
			} catch (SerializationException e) {
				e.printStackTrace();
			}
        }
        return session;
    }

    // 更新session的最后一次访问时间
    @Override
    protected void doUpdate(Session session) {
    	log.info("doUpdate sessionId={}", session.getId().toString());
        super.doUpdate(session);
        Serializable sessionId = session.getId();
        try {
			redisService.setObject(prefix + sessionId.toString(), serializer.serialize(session), 30*60l);
		} catch (SerializationException e) {
			e.printStackTrace();
		}
        
    }

    // 删除session
    @Override
    protected void doDelete(Session session) {
   	 log.info("doUpdate sessionId={}", session.getId().toString());
        super.doDelete(session);
        redisService.remove(prefix + session.getId().toString());
    }
}
